package com.situ.study.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.catalina.filters.AddDefaultCharsetFilter;

import com.situ.study.entity.User;

public class UserServlet extends HttpServlet {

	// 访问Servlet默认访问service方法
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 解决post请求乱码问题,放在service方法最上面
		req.setCharacterEncoding("UTF-8");
		
		System.out.println("UserServlet  service");
		// /JavaWeb1906/user?method=deleteById&id=1
		String method = req.getParameter("method");
		switch (method) {
		case "findAll":
			findAll(req, resp);
			break;
		case "deleteById":
			deleteById(req, resp);
			break;
		case "add":
			add(req, resp);
			break;
		default:
			break;
		}

	}

	private void add(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String name = req.getParameter("name");
		String age = req.getParameter("age");// "23"
		String gender = req.getParameter("gender");
		
		try {
			Class.forName("com.mysql.jdbc.Driver");
			Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/taishan?useUnicode=true&characterEncoding=UTF-8", "root", "1234");
			String sql = "INSERT INTO user(name,age,gender) VALUES(?,?,?);";
			PreparedStatement preparedStatement = connection.prepareStatement(sql);
			// 设置?对应的值
			preparedStatement.setString(1, name);
			preparedStatement.setInt(2, Integer.parseInt(age));
			preparedStatement.setString(3, gender);
			System.out.println(preparedStatement);
			int count = preparedStatement.executeUpdate();
			if (count == 1) {
				System.out.println("插入成功");
			} else {
				System.out.println("插入失败");
			}
			
			// 删除完了之后重定向到/user?method=findAll
			resp.sendRedirect("/JavaWeb1906/user?method=findAll");
			
			// 6、关闭连接
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}

	private void deleteById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String id = req.getParameter("id"); // "3"
		try {
			Class.forName("com.mysql.jdbc.Driver");
			Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/taishan?useUnicode=true&characterEncoding=UTF-8", "root", "1234");
			String sql = "DELETE FROM user WHERE id=?";
			PreparedStatement preparedStatement = connection.prepareStatement(sql);
			// 设置?对应的值
			preparedStatement.setInt(1, Integer.parseInt(id));
			System.out.println(preparedStatement);
			int count = preparedStatement.executeUpdate();
			if (count == 1) {
				System.out.println("删除成功");
			} else {
				System.out.println("删除失败");
			}
			
			// 删除完了之后重定向到/user?method=findAll
			resp.sendRedirect("/JavaWeb1906/user?method=findAll");
			
			// 6、关闭连接
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	private void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 1、加载驱动Class.forName("");
		try {
			Class.forName("com.mysql.jdbc.Driver");
			// 2、获得连接对象Connection
			Connection connection = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/taishan?useUnicode=true&characterEncoding=UTF-8", "root", "1234");
			// 3、写sql语句
			String sql = "SELECT id,name,age,gender FROM user";
			// 4、创建Statement
			PreparedStatement preparedStatement = connection.prepareStatement(sql);
			// 5、执行sql语句
			// (1) 更新类（更改了表里面数据）：delete/update/insert executeUpdate()
			// 返回值：int，表示你影响的行数
			// (2)查询（没有改变表里面数据）: select executeQuery()
			// 返回值：结果集ResultSet
			System.out.println(preparedStatement);
			ResultSet resultSet = preparedStatement.executeQuery();
			ArrayList<User> list = new ArrayList<>();
			// 判断有没有下一个
			while (resultSet.next()) {
				// 遍历每一行，一个字段一个字段拿出对应的数据，
				// 最终将这些数据封装成一个User对象
				int id = resultSet.getInt("id");
				String name = resultSet.getString("name");
				int age = resultSet.getInt("age");
				String gender = resultSet.getString("gender");
				User user = new User(id, name, age, gender);
				list.add(user);
			}
			for (User user : list) {
				System.out.println(user);
			}

			// 将list放到request中，理解成放到一块内存区域
			req.setAttribute("list", list);
			// 转发到user_list.jsp进行展示
			req.getRequestDispatcher("/user_list.jsp").forward(req, resp);

			// 6、关闭连接
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}
}
